use rocket::request::Form;
use rocket::response::Responder;
use rocket_contrib::json::Json;

use common::pagination::Pagination;
use common::result::Action;
use model::IdModel;
use model::post::{PostNew, PostPage, PostUpdate};
use service::POST_SERVICE;

#[get("/post/list")]
pub fn list_posts() -> impl Responder<'static> {
    let posts = POST_SERVICE.list_posts();
    Action::ok(posts)
}

#[get("/post/page?<page..>")]
pub fn page(page: Option<Form<PostPage>>) -> impl Responder<'static> {
    if page.is_none() {
        return Action::ok(Pagination::empty())
    }
    let page_info = POST_SERVICE.page(page.unwrap().0);
    Action::ok(page_info)
}

#[get("/post/get/<id>")]
pub fn get_by_id(id: i32) -> impl Responder<'static> {
    let result = POST_SERVICE.get_by_id(id);
    if result.is_ok() {
        return Action::ok(result.unwrap())
    } else {
        panic!("no record")
    }
}

#[post("/post/add", data = "<post>")]
pub fn add(post: Json<PostNew>) -> impl Responder<'static> {
    POST_SERVICE.add(&post);
    Action::empty()
}

#[post("/post/update", data = "<post>")]
pub fn update(post: Json<PostUpdate>) -> impl Responder<'static> {
    POST_SERVICE.update(&post);
    Action::empty()
}

#[post("/post/delete", data = "<post>")]
pub fn delete(post: Json<IdModel>) -> impl Responder<'static> {
    POST_SERVICE.delete(post.id);
    Action::empty()
}
